﻿namespace Aliphant.Mvvm.XEvent.Events.Base.SubScription
{
    public class EventSubScriptionToken<T> : ISubScriptionToken
    {
        private readonly Delegate _action;
        private readonly Delegate _filter;

        public Action<T> Action => (Action<T>)_action;
        public Predicate<T> Filter => (Predicate<T>)_filter;

        public SubScriptionToken SubScription { get; set; }

        public EventSubScriptionToken(Delegate @action, Delegate @filter)
        {
            _action = @action;
            _filter = @filter;
        }

        public Action<object[]> GetExecutionStrategy()
        {
            Action<T> action = Action;
            Predicate<T> filter = Filter;
            if (action != null && filter != null)
            {
                return delegate (object[] arguments)
                {
                    T val = default;
                    if (arguments != null && arguments.Length != 0 && arguments[0] != null)
                    {
                        val = (T)arguments[0];
                    }
                    if (filter(val))
                    {
                        InvokeAction(action, val);
                    }
                };
            }
            return null;
        }

        public virtual void InvokeAction(Action<T> action, T argument)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            action(argument);
        }


    }
}
